# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: log_util.py
# Time: 13:45

import logging
import os
import time

from common.util.file_util import get_log_path


class GenerateLog():
    def __init__(self):
        self.log_path = get_log_path()
        self.level = logging.DEBUG
        self.log_file = os.path.join(self.log_path, "{}.log".format(time.strftime("'%Y-%m-%d_%H_%M", time.localtime())))
        self.loggers = logging.getLogger(__name__)
        self.formatter = logging.Formatter(
            "%(asctime)s file: %(filename)s line: %(lineno)d - %(levelname)s - %(message)s")

    def console_logger(self):
        '''
        将信息打印到控制台
        :return:
        '''
        self.loggers.setLevel(level=self.level)
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(self.formatter)
        self.loggers.addHandler(console)
        return self.loggers

    def file_logger(self):
        '''
        将信息写入到日志文件，如果路径不存在则自动生成
        :return: logger对象
        '''
        self.loggers.setLevel(level=self.level)
        handler = logging.FileHandler(self.log_file, encoding="utf-8")
        handler.setLevel(level=self.level)
        handler.setFormatter(self.formatter)
        self.loggers.addHandler(handler)
        return self.loggers


    def logger(self):
        '''
        讲信息输出到控制台且合并写入文件
        :return: logger对象
        '''
        self.loggers.setLevel(level=self.level)
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(self.formatter)

        handler = logging.FileHandler(self.log_file, encoding="utf-8")
        handler.setLevel(level=self.level)
        handler.setFormatter(self.formatter)

        self.filter_adb_log()
        self.loggers.addHandler(console)
        self.loggers.addHandler(handler)
        return self.loggers

    def filter_adb_log(self):
        # 设置adb的log打印级别
        logger = logging.getLogger("airtest")
        logger.setLevel(logging.ERROR)

if __name__ == '__main__':
    log = GenerateLog().logger()
    log.error("测试")
